/*
 * RtpMediaFormat.cpp
 *
 *  Created on: 2016年5月1日
 *      Author: terry
 */

#include "RtpMediaFormat.h"
#include "URI.h"
#include "TStringUtil.h"
#include "TProperties.h"

const char* RtpMediaFormat::AUDIO = "audio";
const char* RtpMediaFormat::VIDEO = "video";

const char*	RtpMediaFormat::RTP_OVER_TCP = "tcp";
const char*	RtpMediaFormat::RTP_OVER_UDP = "rtp";


int RtpMediaFormat::makePayload(const std::string& codec)
{
	if (codec == "PCMU")
	{
		return 0;
	}
	else if (codec == "PCMA")
	{
		return 8;
	}
	else if (codec == "H264")
	{
		return 96;
	}
	else if (codec == "HEVC")
	{
		return 97;
	}
	else
	{
		return 99;
	}
}

RtpMediaFormat::RtpMediaFormat():
	m_protocol(RTP_OVER_UDP),
	m_ip(),
	m_port(),
	m_name(),
	m_codec(),
	m_clockRate(),
	m_payload(),
	m_channels()
{
	m_ip = "0.0.0.0";
}

RtpMediaFormat::~RtpMediaFormat()
{
}

std::string RtpMediaFormat::toUrl() const
{
	return comn::StringUtil::format("%s://%s:%d/%s?pt=%d&codec=%s&clock=%d&channel=%d&fmtp=%s",
			m_protocol.c_str(),
			m_ip.c_str(), m_port, m_name.c_str(),
			m_payload, m_codec.c_str(), m_clockRate, m_channels,
			m_fmtp.c_str());
}

bool RtpMediaFormat::parse(const std::string& url)
{
	util::Uri uri;
	if (!uri.parse(url))
	{
		return false;
	}

	m_protocol = uri.m_scheme;
	m_ip = uri.m_host;
	m_port = uri.m_port;
	m_name = uri.m_path;

	comn::Properties props;
	props.parse(uri.m_query.c_str(), uri.m_query.size(), '=', '&');

	props.get("pt", m_payload);
	props.get("codec", m_codec);
	props.get("clock", m_clockRate);
	props.get("channel", m_channels);
	props.get("fmtp", m_fmtp);

	return true;
}

bool RtpMediaFormat::empty() const
{
	return m_ip.empty() || m_codec.empty();
}
